package servlets;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import actionForm.CreateContactValidationForm;
import domain.Contact;
import domain.IDAOContact;

public class CreateContactAction extends Action {
	public ActionForward execute(final ActionMapping pMapping,
			ActionForm pForm, final HttpServletRequest request,
			final HttpServletResponse response) {
		if (request.getMethod().equals("POST")) {
			ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServlet().getServletContext());
			IDAOContact dao = (IDAOContact) context.getBean("daocontact");
			final CreateContactValidationForm
			lForm=(CreateContactValidationForm)pForm;
			final String firstName = lForm.getFirstName();
			final String lastName = lForm.getLastName();
			final String email = lForm.getEmail();
			final String street = lForm.getStreet();
			final String zip = lForm.getZip();
			final String country = lForm.getCountry();
			final String city = lForm.getCity();
			final String phoneKind = lForm.getPhoneKind();
			final String phoneNumber = lForm.getPhoneNumber();
			String numSiret = null;
			final String[] groupIds = lForm.getGroupIds();
			final String society = lForm.getSociety();
			ArrayList<Long> groupeIdsList = new ArrayList<Long>();
			// create a new Contact
			if( groupIds != null) {
					for(String groupId : groupIds)
						groupeIdsList.add(Long.valueOf(groupId));
			}
			//		
			if(society != null){
				numSiret = lForm.getNumSiret();
			}
			final Contact lError = dao.addContact(firstName, lastName, email, zip, city, country, street, phoneKind, phoneNumber,  groupeIdsList, numSiret);
			if(lError != null){
				request.setAttribute("successMessage", "The contact has been created.");
				return pMapping.findForward("success");
			} else {
				request.setAttribute("errorMessage", "The contact could not be created.");
				return pMapping.findForward("error");
			}
		}
		return null;
	}
}